package com.example.activemq.topic;

import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.jms.*;


/**
 * Created by Dev11 on 2019/10/11.
 */
@Component
@Slf4j
public class TopicMessageProducer {

    @Autowired
    private JmsTemplate jmsTemplate;

    @Autowired
    ActiveMQConnectionFactory connectionFactory;

    @Resource(name="activeMQTopic")
    private ActiveMQTopic activeMQTopic;

    public void sendMessage(String msg) {
        jmsTemplate.convertAndSend(activeMQTopic, msg);
    }


/*  // 原生方式
    public void sendMessage(final String topic, final String message) {
        Connection connection = null;
        Session session = null;
        try {
            connection = connectionFactory.createConnection();
            connection.start();

            session=connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Destination destination=session.createTopic(topic);
            MessageProducer producer=session.createProducer(destination);

            TextMessage textMessage=session.createTextMessage(message);
            producer.send(textMessage);
        } catch (Exception e) {
            log.error("主题消息发送失败", e);
        }finally {
            try {
                if (connection != null) {
                    connection.close();
                }
                if (session != null) {
                    session.close();
                }
            } catch (JMSException e) {
                log.error("MQ连接关闭失败", e);
            }
        }
    }*/
}
